package com.example.rule.engine;

import com.example.rule.entity.po.RulePO;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

@RequiredArgsConstructor
@Component
public class GroovyEngine extends BaseEngine {

    private final GroovyShell groovyShell;

    @Override
    public double execute(List<RulePO> tasks) {
        int successCount = 0;

        for (RulePO task : tasks) {
            try {
                Binding binding = new Binding();
                binding.setVariable("data", task.getData());

                // 使用正确的 Groovy 3.x API
                Script script = groovyShell.parse(String.format("return %s", task.getExpression()));
                script.setBinding(binding);
                Object result = script.run();
                
                if (result instanceof Boolean && Boolean.TRUE.equals(result)) {
                    successCount++;
                }
            } catch (Exception e) {
                // 可记录日志或跳过异常表达式
                System.err.println("规则执行异常: " + e.getMessage());
            }
        }

        return tasks.isEmpty() ? 0.0 : (double) successCount / tasks.size();
    }
}
